import tensorflow as tf
import pandas as pd
import numpy as np
import  cv2
import matplotlib.pyplot as plt
from sklearn.utils import  shuffle

#设置学习率，样本个数
train_epoch=50
learn_rate=0.01
df=pd.read_csv('C:/Users/de/Desktop/demo2/boston.csv',header=0)
df=df.values
df=np.array(df)
#前12行的数据

for i in range(12):
    df[:,i]=(df[:,i]-df[:,i].min())/(df[:,i].max()-df[:,i].min())
x_data = df[:,:12]
y_data = df[:, 12]
#定义特征数据，占位符
x=tf.placeholder(tf.float32,[None,12],name='x')
y=tf.placeholder(tf.float32,[None,1],name='y')

w=tf.Variable(tf.random_normal([12,1],stddev=0.01),name='W')
b=tf.Variable(1.0,name='b')
def model(x,w,b):
    return tf.matmul(x,w)+b
pred=model(x,w,b)

with tf.name_scope("lossFunction"):
    loss_function=tf.reduce_mean(tf.pow(y-pred,2))

optimizer=tf.train.GradientDescentOptimizer(learn_rate).minimize(loss_function)
init=tf.global_variables_initializer()
#模型训练
sess=tf.Session()
sess.run(init)
loss_list=[]
for epoch in range(train_epoch):
        loss_sum=0.0
        for xs,ys in zip(x_data,y_data):
            xs=xs.reshape(1,12)
            ys=ys.reshape(1,1)

            _,loss=sess.run([optimizer,loss_function],feed_dict={x:xs,y:ys})
            loss_sum=loss_sum+loss
            loss_list.append(loss)

            xvalues,yvalues=shuffle(x_data,y_data)

            b0temp=b.eval(session=sess)
            w0temp=w.eval(session=sess)
            loss_average=loss_sum/len(y_data)
            print("epoch=",epoch+1,'loss=',loss_average,'b=',b0temp,'w=',w0temp)
n=np.random.randint(506)
print(n+2)
x_test=x_data[n]
x_test=x_test.reshape(1,12)
predict=sess.run(pred,feed_dict={x:x_test})
print('预测一下：',predict)
target=y_data[n]
print('原来的数据是：', target)
# plt.plot(loss_list)



